1918D - Blocking Elements - CodeForces Solution


binary search data structures dp implementation two pointers

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
using namespace std;

#define int long long int
#define pb push_back
#define size(a) a.size()
#define traverse(a) for (int i = 0; i < size(a); i++)
#define mod 1000000007
#define cdv vector<vector<int>>
#define cv vector<int>
#define range(v) v.begin(), v.end()
#define loop(i, a, b) for (int i = a; i <= b; i++)
#define rloop(i, a, b) for (int i = a; i >= b; i--)
#define ff first
#define ss second

bool check(int val, cv &v)
{
    int n = size(v) - 1;
    cdv dp(n + 1, cv(2, 0));
    map<int, int> mp;
    mp[0] = 0;
    loop(i, 1, n)
    {
        dp[i][1] = v[i] - v[i - 1] + min(dp[i - 1][0], dp[i - 1][1]);
        while (1){
            auto it = mp.end();
            it--;
            if (it->ss >= dp[i][1]) mp.erase(it);
            else break;
        }
        mp[v[i]] = dp[i][1];
        dp[i][0] = mp.lower_bound(v[i] - val)->ss;
    }
    if (min(dp[n][0], dp[n][1]) <= val) return 1;
    return 0;
}

int bs(int l, int r, cv &v)
{
    if (l == r) return l;
    int mid = (l + r) / 2;
    if (check(mid, v)) return bs(l, mid, v);
    else return bs(mid + 1, r, v);
}

void fun()
{
    int ans = 0;
    int n; cin >> n;
    map<int, int> mp;
    cv v(n + 1, 0);
    traverse(v)
    {
        if (i == 0) continue;
        cin >> v[i];
        v[i] += v[i - 1];
    }
    cout << bs(0, 1e14, v) << endl;
}

int32_t main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    int n;
    cin >> n;
    while (n--)
        fun();
}


Comments

Submit
0 Comments
More Questions

630C - Lucky Numbers
1208B - Uniqueness
1384A - Common Prefixes
371A - K-Periodic Array
1542A - Odd Set
1567B - MEXor Mixup
669A - Little Artem and Presents
691B - s-palindrome
851A - Arpa and a research in Mexican wave
811A - Vladik and Courtesy
1006B - Polycarp's Practice
1422A - Fence
21D - Traveling Graph
1559B - Mocha and Red and Blue
1579C - Ticks
268B - Buttons
898A - Rounding
1372B - Omkar and Last Class of Math
1025D - Recovering BST
439A - Devu the Singer and Churu the Joker
1323A - Even Subset Sum Problem
1095A - Repeating Cipher
630F - Selection of Personnel
630K - Indivisibility
20B - Equation
600B - Queries about less or equal elements
1015A - Points in Segments
1593B - Make it Divisible by 25
680C - Bear and Prime 100
1300A - Non-zero